const db = uniCloud.databaseForJQL()
const _ = db.command


import { getGridCode,getSurroundingGrids } from "./getSurroundingGrids";


export const isPointInPolygon = (point, polygon) => {


	let intersections = 0;
	for (let i = 0; i < polygon.length; i++) {
		let currentVertex = polygon[i];
		let nextVertex = polygon[(i + 1) % polygon.length];
		if ((currentVertex[1] > point.latitude) !== (nextVertex[1] > point.latitude) &&
			point.longitude < (nextVertex[0] - currentVertex[0]) * (point.latitude - currentVertex[1]) / (
				nextVertex[1] - currentVertex[1]) + currentVertex[0]) {
			intersections++;
		}
	}

	return intersections % 2 === 1;
};
export const getPolygon = (polygon) => {

	const points = [];
	for (let i = 0; i < polygon.length; i++) {
		const [longitude, latitude] = polygon[i];
		const point = {
			longitude,
			latitude
		};
		points.push(point);
	}
	return {
		points: points,
		strokeWidth: 2,
		strokeColor: '#55aa7f',
		fillColor: 'rgba(0, 0, 0, 0.1)',
	}

}
export async function getGroup(location) {
//在视野范围内是否有群（不等于入群）
	try {
		const centerGrids=getGridCode(location)
        const grids=getSurroundingGrids(centerGrids,10)
		const groups= await db.collection('Group').where({
			grid:_.in(grids)
		}).get()
	                                        
		//是否在群服务范围内

		if (groups.data && groups.data.length > 0) {
		  return groups.data.find(group => 
		    group.aMapLocation?.length > 0 && 
		    isPointInPolygon(location, group.aMapLocation)
		  ) || null; // 如果没找到匹配项，显式返回null
		}
		
		return null;

	} catch (e) {
		console.error("找群数据错误",e)
		return null
	}



}